//index.js
//获取应用实例
var cfg = require('../../utils/cfg');
var util = require('../../utils/util');
const app = getApp();
const { $Toast } = require('../../dist/base/index');
var common = require('../../utils/common');
var sendRequest = require('../../utils/requestUtils');

Page({
  data: {
    merchant: {},
    selAreaId: '-1',
    pictureUrl: '',
    applyButtonHidden: true,
    tempFilePaths: []
  },
  onLoad: function () {
    let that = this;
    that.loadMerchant();
  },

  loadMerchant : function() {
    let that = this;
    sendRequest.sendReq(cfg.djurl.loadMerchant, {
      openId: 'xxx'
    }, function (result) {
      that.setData({
        merchant: result.data,
        pictureUrl: result.data.pictureUrl
      });
    });
  },

  //保存店铺信息
  updateInfo: function () {
    let that = this;
    if (that.data.merchant.merchantName == '' || that.data.merchant.merchantName == undefined) {
      util.alert('请输入店铺名称');
      return;
    }

    if (that.data.merchant.phone == '' || that.data.merchant.phone == undefined) {
      util.alert('请输入手机号码');
      return;
    }

    if (that.data.tempFilePaths.length == 0) {
      sendRequest.sendReq(cfg.djurl.modifyInfo, {
        'merchantName': that.data.merchant.merchantName,
        'phone': that.data.merchant.phone,
        'openId': 'xxx'
      }, function (result) {
        console.log('修改成功');
        wx.reLaunch({
          url: '/pages/home/home'
        })
      });

      return;
    }

    wx.uploadFile({
      url: cfg.host + cfg.djurl.modifyInfo,
      filePath: that.data.tempFilePaths[0],
      name: 'file',
      formData: {
        'merchantName': that.data.merchant.merchantName,
        'phone': that.data.merchant.phone,
        'openId': 'xxx'
      },
      success(res) {
        let result = JSON.parse(res.data);
        if (result.code !== 1000) {
          util.alert(result.message);
          return;
        }

        console.log('修改成功');
        wx.reLaunch({
          url: '/pages/home/home'
        })

      }
    })

  },

  choseImg: function () {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        // tempFilePath可以作为img标签的src属性显示图片
        that.data.tempFilePaths = res.tempFilePaths;
        console.log('>>>res.tempFilePaths=' + res.tempFilePaths[0]);
        that.setData({
          pictureUrl: res.tempFilePaths[0],
          applyButtonHidden: false
        });
      }
    })
  },

  merchantNameChange: function (event) {
    this.data.merchant.merchantName = event.detail.detail.value;
  },

  phoneChange: function (event) {
    this.data.merchant.phone = event.detail.detail.value;
  }

})
